<template>
    <div class="out">
        <el-text class="span" type="primary">{{ info.username }}</el-text>
        <el-dropdown class="dropdown" trigger="click">
            <el-avatar :src="`/api/images/${info.picture}`"/>
            <template #dropdown>
                <el-dropdown-menu v-show="info.bool">
                    <el-dropdown-item @click="openDrawer">健康打卡</el-dropdown-item>
                </el-dropdown-menu>
                <el-dropdown-menu>
                    <el-dropdown-item @click="changePwd">修改密码</el-dropdown-item>
                </el-dropdown-menu>
                <el-dropdown-menu>
                    <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
                <el-dropdown-menu>
                    <el-dropdown-item divided>
                        <el-link :underline="false" href="https://element-plus.org/zh-CN/" target="_blank">组件库
                        </el-link>
                    </el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
    </div>
    <el-dialog
            v-model="pwdDia"
            width="20%"
            @close="reset"
    >
        <div class="form">
            <el-form
                    ref="ruleFormRef"
                    :model="ruleForm"
                    :rules="rules"
                    class="demo-ruleForm"
                    label-width="0"
            >
                <el-form-item prop="oldPassword">
                    <el-input v-model="ruleForm.oldPassword" autocomplete="off" clearable placeholder="请输入原始密码"
                              show-password/>
                </el-form-item>
                <el-form-item prop="newPassword">
                    <el-input v-model="ruleForm.newPassword" autocomplete="off" clearable placeholder="请输入修改密码"
                              show-password/>
                </el-form-item>
                <el-form-item prop="checkPass">
                    <el-input
                            v-model="ruleForm.checkPass"
                            autocomplete="off" clearable placeholder="请再次输入修改密码" show-password
                    />
                </el-form-item>
                <div style="display: flex; justify-content: space-around;margin-top: 20px">
                    <el-button @click="reset">
                        刷新
                    </el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        确定
                    </el-button>
                </div>
            </el-form>
        </div>
    </el-dialog>
    <div class="drawer">
        <el-drawer
                v-model="drawer"
                direction="ltr"
                size="20%"
                title="请填写健康信息"
        >
            <el-scrollbar>
                <div class="healthForm">
                    <el-avatar :size="100" :src="`/api/images/${info.picture}`"/>
                    <el-text class="span" size="large" type="primary">{{ info.username }}</el-text>
                    <el-divider>
                        <el-icon>
                            <star-filled/>
                        </el-icon>
                    </el-divider>
                    <el-alert :closable="false" center description="体温达到39℃以上，请立即与管理员沟通！！！"
                              style="height: 40px;margin-bottom: 10px"
                              type="warning"/>
                    <div class="form">
                        <el-form ref="ruleRef" :model="form" :rules="rrlues" label-width="0">
                            <el-form-item prop="temper">
                                <el-input-number v-model="form.temper" :max="42" :precision="2" :step="0.01"
                                                 placeholder="请输入温度（单位（℃））" style="width: 85%"/>
                            </el-form-item>
                            <el-form-item prop="headache">
                                <el-select v-model="form.headache" placeholder="是否头痛">
                                    <el-option v-for="item in headacheOption" :key="item.label" :label="item.label"
                                               :value="item.value"/>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="fever">
                                <el-select v-model="form.fever" placeholder="是否发烧">
                                    <el-option v-for="item in headacheFever" :key="item.label" :label="item.label"
                                               :value="item.value"/>
                                </el-select>
                            </el-form-item>
                            <el-form-item prop="remark">
                                <el-input v-model="form.remark" placeholder="请输入其他健康问题（默认为无）"
                                          style="width: 85%"
                                          type="textarea"/>
                            </el-form-item>
                        </el-form>
                    </div>
                </div>
            </el-scrollbar>
            <template #footer>
                <div style="flex: auto">
                    <el-button type="primary" @click="postHealth(ruleRef)">提交</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script lang='ts' setup>
import { LoginService, StaffService } from '@/api'
import { Message, Notification } from '@/plugins/element'
import { useRouter } from 'vue-router'
import { logout_one, logout_two, useStaff } from '@/store'
import { storeToRefs } from 'pinia'
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { md5Pwd } from '@/utils/commonUtils'
import { Password } from '@/ts/type'
import { StarFilled } from '@element-plus/icons-vue'
import { Health } from '@/ts/type/Health'
import { rules as rrlues } from '@/config/formConfig'
import HealthService from '@/api/healthApi'
import { EventBus } from '@/utils/mitt'

const drawer = ref<boolean>(false)
const ruleFormRef = ref<FormInstance>()
const ruleRef = ref<FormInstance>()
const pwdDia = ref<boolean>(false)
const Staff = useStaff()
const { info } = storeToRefs(Staff)
const router = useRouter()
const form = ref<Health>({ temper: 25 })
const pwd = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请输入修改密码'))
  } else {
    if (ruleForm.checkPass !== '') {
      if (!ruleFormRef.value) return
      ruleFormRef.value.validateField('checkPass', () => null)
    }
    callback()
  }
}
const checkPwd = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入修改密码'))
  } else if (value !== ruleForm.newPassword) {
    callback(new Error('两次修改密码输入不匹配'))
  } else {
    callback()
  }
}

const headacheOption = [
  { label: '头痛', value: 1 },
  { label: '正常', value: 0 }
]

const headacheFever = [
  { label: '发烧', value: 1 },
  { label: '正常', value: 0 }
]

const reset = () => {
  ruleFormRef.value?.resetFields()
  ruleRef.value?.resetFields()
}

const ruleForm = reactive({
  oldPassword: '',
  newPassword: '',
  checkPass: '',
})

const rules = reactive<FormRules>({
  oldPassword: [{ required: true, trigger: 'blur', message: '请输入原始密码' }],
  newPassword: [{ validator: pwd, trigger: 'blur' }],
  checkPass: [{ validator: checkPwd, trigger: 'blur' }],
})
const changePwd = () => {
  pwdDia.value = !pwdDia.value
}

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  const form: Password = {
    id: useStaff().info.staffId,
    oldPassword: md5Pwd(ruleForm.oldPassword),
    newPassword: md5Pwd(ruleForm.checkPass)
  }
  formEl.validate(valid => {
    if (valid) {
      StaffService.changePwd(form).then(res => {
        const { data } = res
        pwdDia.value = !pwdDia.value
        ruleFormRef.value?.resetFields()
        Notification.success(data)
      })
    }
  })
}

// 打开抽屉
const openDrawer = () => {
  drawer.value = true
}

// 健康打卡
const postHealth = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  if (form.value.temper as number <= 32.50) return Message.error('请输入正确的身体温度！！')
  formEl.validate(valid => {
    if (valid) {
      HealthService.postHealth(form.value).then(res => {
        const { data } = res
        EventBus.emit('searchHealth', false)
        drawer.value = false
        Notification.success(data)
      })
    }
  })
}

const logout = async () => {
  await LoginService.logout().then(async res => {
    logout_one()
    await router.push('/login')
    logout_two()
    Notification.success(res)
  })
}
</script>

<style lang='scss' scoped>
.healthForm {
  display: flex;
  align-items: center;
  flex-direction: column;
  justify-content: center;
}

.out {
  margin: 0 5px;
}

.span {
  margin-right: 10px;
}

.dropdown {
  margin: 5px 0;
}
</style>